<template>
  <a-modal
    :open="open"
    :title="isEdit ? '编辑态势对象' : '新建态势对象'"
    width="900px"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :maskClosable="true"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-divider orientation="left">基础信息</a-divider>

      <a-form-item label="对象类型" name="object_type" :rules="[{ required: true, message: '请选择对象类型' }]">
        <a-select v-model:value="formData.object_type" placeholder="请选择对象类型" :disabled="isEdit" @change="!isEdit && handleObjectTypeChange($event)">
          <a-select-option v-for="type in objectTypes" :key="type.value" :value="type.value">
            <a-tag :color="type.color" style="margin-right: 8px">{{ type.label }}</a-tag>
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 所有对象类型的装备类别 -->
      <a-form-item
        v-if="formData.object_type"
        label="装备类别"
        name="equipment_category"
        :rules="[{ required: true, message: '请选择装备类别' }]"
      >
        <a-select
          v-model:value="formData.equipment_category"
          placeholder="请选择装备类别"
          @change="!isEdit && handleEquipmentCategoryChange($event)"
          :disabled="isEdit"
          :loading="equipmentCategories.length === 0 && formData.object_type"
        >
          <a-select-option v-for="category in equipmentCategories" :key="category.value" :value="category.value">
            {{ category.label }}
          </a-select-option>
          <a-select-option v-if="equipmentCategories.length === 0 && formData.object_type" disabled>
            正在加载装备类别...
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
        <a-input v-model:value="formData.name" placeholder="请输入名称" />
      </a-form-item>

      <a-form-item label="编码" name="code">
        <a-input v-model:value="formData.code" placeholder="请输入唯一编码" />
      </a-form-item>

      <a-form-item label="型号" name="model">
        <a-input v-model:value="formData.model" placeholder="请输入型号" />
      </a-form-item>

      <a-form-item label="所属单位" name="organization">
        <a-input v-model:value="formData.organization" placeholder="请输入所属单位" />
      </a-form-item>

      <a-form-item label="部署状态" name="deployment_status">
        <a-select v-model:value="formData.deployment_status" placeholder="请选择部署状态">
          <a-select-option v-for="status in deploymentStatuses" :key="status.value" :value="status.value">
            {{ status.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="描述" name="description">
        <a-textarea v-model:value="formData.description" placeholder="请输入对象描述" :rows="3" :maxlength="200" showCount />
      </a-form-item>

      <a-divider orientation="left" v-if="formData.object_type">
        类型特定字段 - {{ getTypeLabel(formData.object_type) }}
      </a-divider>

      <!-- 观测装备专属字段 -->
      <template v-if="formData.object_type === 'observation_equipment' && formData.equipment_category">
        <!-- 雷达专用字段 -->
        <template v-if="formData.equipment_category === 'radar'">
          <a-form-item label="探测距离(km)">
            <a-input-number v-model:value="formData.type_specific_data.detection_range" :min="0" style="width: 100%" placeholder="请输入探测距离" />
          </a-form-item>
          <a-form-item label="工作频率">
            <a-input v-model:value="formData.type_specific_data.frequency" placeholder="请输入工作频率" />
          </a-form-item>
          <a-form-item label="分辨率">
            <a-input v-model:value="formData.type_specific_data.resolution" placeholder="请输入分辨率" />
          </a-form-item>
          <a-form-item label="扫描速率(rpm)">
            <a-input-number v-model:value="formData.type_specific_data.scan_rate" :min="0" style="width: 100%" placeholder="请输入扫描速率" />
          </a-form-item>
        </template>

        <!-- 光学专用字段 -->
        <template v-if="formData.equipment_category === 'optical'">
          <a-form-item label="探测距离(km)">
            <a-input-number v-model:value="formData.type_specific_data.detection_range" :min="0" style="width: 100%" placeholder="请输入探测距离" />
          </a-form-item>
          <a-form-item label="分辨率">
            <a-input v-model:value="formData.type_specific_data.resolution" placeholder="请输入分辨率" />
          </a-form-item>
          <a-form-item label="焦距(mm)">
            <a-input-number v-model:value="formData.type_specific_data.focal_length" :min="0" style="width: 100%" placeholder="请输入焦距" />
          </a-form-item>
          <a-form-item label="视场角">
            <a-input v-model:value="formData.type_specific_data.field_of_view" placeholder="请输入视场角" />
          </a-form-item>
        </template>

        <!-- 声纳专用字段 -->
        <template v-if="formData.equipment_category === 'sonar'">
          <a-form-item label="探测距离(km)">
            <a-input-number v-model:value="formData.type_specific_data.detection_range" :min="0" style="width: 100%" placeholder="请输入探测距离" />
          </a-form-item>
          <a-form-item label="工作频率(kHz)">
            <a-input-number v-model:value="formData.type_specific_data.frequency" :min="0" style="width: 100%" placeholder="请输入工作频率" />
          </a-form-item>
          <a-form-item label="声功率">
            <a-input-number v-model:value="formData.type_specific_data.acoustic_power" :min="0" style="width: 100%" placeholder="请输入声功率" />
          </a-form-item>
          <a-form-item label="波束宽度">
            <a-input v-model:value="formData.type_specific_data.beam_width" placeholder="请输入波束宽度" />
          </a-form-item>
        </template>

        <!-- 电子侦察专用字段 -->
        <template v-if="formData.equipment_category === 'elint'">
          <a-form-item label="侦测距离(km)">
            <a-input-number v-model:value="formData.type_specific_data.detection_range" :min="0" style="width: 100%" placeholder="请输入侦测距离" />
          </a-form-item>
          <a-form-item label="频率范围">
            <a-input v-model:value="formData.type_specific_data.frequency_range" placeholder="请输入频率范围" />
          </a-form-item>
          <a-form-item label="灵敏度">
            <a-input v-model:value="formData.type_specific_data.sensitivity" placeholder="请输入灵敏度" />
          </a-form-item>
          <a-form-item label="信号类型">
            <a-select v-model:value="formData.type_specific_data.signal_types" mode="multiple" placeholder="请选择信号类型">
              <a-select-option value="通信信号">通信信号</a-select-option>
              <a-select-option value="雷达信号">雷达信号</a-select-option>
              <a-select-option value="导航信号">导航信号</a-select-option>
              <a-select-option value="遥测信号">遥测信号</a-select-option>
            </a-select>
          </a-form-item>
        </template>

        <!-- 卫星专用字段 -->
        <template v-if="formData.equipment_category === 'satellite'">
          <!-- 基本信息 -->
          <a-form-item label="卫星名称">
            <a-input v-model:value="formData.type_specific_data.name" placeholder="请输入卫星名称" />
          </a-form-item>
          <a-form-item label="运行状态">
            <a-select v-model:value="formData.type_specific_data.status" placeholder="请选择运行状态">
              <a-select-option value="online">在线</a-select-option>
              <a-select-option value="offline">离线</a-select-option>
              <a-select-option value="maintenance">维护中</a-select-option>
              <a-select-option value="decommissioned">退役</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="是否活跃">
            <a-switch v-model:checked="formData.type_specific_data.active" />
          </a-form-item>

          <!-- 轨道参数 -->
          <a-form-item label="轨道类型">
            <a-select v-model:value="formData.type_specific_data.orbit_type" placeholder="请选择轨道类型">
              <a-select-option value="LEO">低轨(LEO)</a-select-option>
              <a-select-option value="MEO">中轨(MEO)</a-select-option>
              <a-select-option value="GEO">地球静止轨道(GEO)</a-select-option>
              <a-select-option value="SSO">太阳同步轨道(SSO)</a-select-option>
              <a-select-option value="极地轨道">极地轨道</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="轨道高度(km)">
            <a-input-number v-model:value="formData.type_specific_data.altitude" :min="0" style="width: 100%" placeholder="请输入轨道高度" />
          </a-form-item>
          <a-form-item label="轨道周期">
            <a-input v-model:value="formData.type_specific_data.orbit_period" placeholder="请输入轨道周期" />
          </a-form-item>
          <a-form-item label="覆盖范围(km²)">
            <a-input-number v-model:value="formData.type_specific_data.coverage" :min="0" style="width: 100%" placeholder="请输入覆盖范围" />
          </a-form-item>

          <!-- 性能参数 -->
          <a-form-item label="分辨率(m)">
            <a-input-number v-model:value="formData.type_specific_data.resolution" :min="0" :precision="1" style="width: 100%" placeholder="请输入分辨率" />
          </a-form-item>
          <a-form-item label="重访周期">
            <a-input v-model:value="formData.type_specific_data.revisit_period" placeholder="请输入重访周期" />
          </a-form-item>

          <!-- 载荷配置 -->
          <a-form-item label="载荷配置">
            <div v-for="(payload, index) in formData.type_specific_data.payload" :key="index" style="margin-bottom: 16px; padding: 16px; border: 1px solid #d9d9d9; border-radius: 6px;">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="载荷类型" style="margin-bottom: 0;">
                    <a-select v-model:value="payload.type" placeholder="载荷类型">
                      <a-select-option value="可见光">可见光</a-select-option>
                      <a-select-option value="SAR">SAR</a-select-option>
                      <a-select-option value="红外">红外</a-select-option>
                      <a-select-option value="多光谱">多光谱</a-select-option>
                      <a-select-option value="高光谱">高光谱</a-select-option>
                      <a-select-option value="导航信号">导航信号</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="分辨率" style="margin-bottom: 0;">
                    <a-input v-model:value="payload.resolution" placeholder="分辨率" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="幅宽" style="margin-bottom: 0;">
                    <a-input v-model:value="payload.swath" placeholder="幅宽" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-button @click="addPayload" type="dashed" size="small" style="width: 100%;">
                <template #icon><PlusOutlined /></template>
                添加载荷
              </a-button>
              <a-button v-if="index > 0" @click="removePayload(index)" type="link" danger size="small">
                删除
              </a-button>
            </div>
            <a-button v-if="!formData.type_specific_data.payload || formData.type_specific_data.payload.length === 0" @click="addPayload" type="dashed" size="small" style="width: 100%;">
              <template #icon><PlusOutlined /></template>
              添加载荷
            </a-button>
          </a-form-item>

          <!-- 通信参数 -->
          <a-form-item label="波段">
            <a-input v-model:value="formData.type_specific_data.band" placeholder="请输入波段" />
          </a-form-item>
          <a-form-item label="带宽">
            <a-input v-model:value="formData.type_specific_data.bandwidth" placeholder="请输入带宽" />
          </a-form-item>

          <!-- 状态监控 -->
          <a-form-item label="电量">
            <a-input v-model:value="formData.type_specific_data.battery" placeholder="例如: 70%" style="width: 120px;" />
          </a-form-item>
          <a-form-item label="燃料">
            <a-input v-model:value="formData.type_specific_data.fuel" placeholder="例如: 60%" style="width: 120px;" />
          </a-form-item>
          <a-form-item label="当前位置">
            <a-input v-model:value="formData.type_specific_data.current_position" placeholder="请输入当前位置坐标(经度,纬度)" />
          </a-form-item>

          <!-- 其他信息 -->
          <a-form-item label="发射时间">
            <a-date-picker
              v-model:value="launchTime"
              style="width: 100%"
              placeholder="请选择发射时间"
              :format="'YYYY-MM-DD'"
              :value-format="'YYYY-MM-DD'"
            />
          </a-form-item>
          <a-form-item label="典型用途">
            <a-textarea v-model:value="formData.type_specific_data.typical_usage" :rows="3" placeholder="请输入典型用途" />
          </a-form-item>
        </template>

        <!-- 无人机专用字段 -->
        <template v-if="formData.equipment_category === 'uav'">
          <a-form-item label="续航时间(小时)">
            <a-input-number v-model:value="formData.type_specific_data.endurance_time" :min="0" :precision="1" style="width: 100%" placeholder="请输入续航时间" />
          </a-form-item>
          <a-form-item label="最大飞行高度(m)">
            <a-input-number v-model:value="formData.type_specific_data.max_altitude" :min="0" style="width: 100%" placeholder="请输入最大飞行高度" />
          </a-form-item>
          <a-form-item label="载荷类型">
            <a-select v-model:value="formData.type_specific_data.payload_type" placeholder="请选择载荷类型">
              <a-select-option value="光电载荷">光电载荷</a-select-option>
              <a-select-option value="雷达载荷">雷达载荷</a-select-option>
              <a-select-option value="多光谱载荷">多光谱载荷</a-select-option>
              <a-select-option value="通信载荷">通信载荷</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="控制距离(km)">
            <a-input-number v-model:value="formData.type_specific_data.control_range" :min="0" style="width: 100%" placeholder="请输入控制距离" />
          </a-form-item>
        </template>
      </template>

      <!-- 基础设施专属字段 -->
      <template v-if="formData.object_type === 'infrastructure'">
        <!-- 新增字段 -->
        <a-form-item label="当前位置">
          <a-input v-model:value="formData.type_specific_data.coordinates" placeholder="请输入当前位置坐标(经度,纬度)" />
        </a-form-item>

        <a-form-item label="重要程度">
          <a-select v-model:value="formData.type_specific_data.importance" placeholder="请选择重要程度">
            <a-select-option value="general">一般</a-select-option>
            <a-select-option value="important">重要</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="发现时间">
          <a-date-picker
            v-model:value="discoveryTime"
            style="width: 100%"
            placeholder="请选择发现时间"
            :format="'YYYY-MM-DD'"
            :value-format="'YYYY-MM-DD'"
          />
        </a-form-item>

        <a-divider />

        <!-- 机场专用字段 -->
        <template v-if="formData.equipment_category === 'airport'">
          <a-form-item label="占地面积(㎡)">
            <a-input-number v-model:value="formData.type_specific_data.area" :min="0" style="width: 100%" placeholder="请输入占地面积" />
          </a-form-item>

          <a-form-item label="跑道长度(m)">
            <a-input-number v-model:value="formData.type_specific_data.runway_length" :min="0" style="width: 100%" placeholder="请输入跑道长度" />
          </a-form-item>

          <a-form-item label="跑道宽度(m)">
            <a-input-number v-model:value="formData.type_specific_data.runway_width" :min="0" style="width: 100%" placeholder="请输入跑道宽度" />
          </a-form-item>

          <a-form-item label="跑道数量">
            <a-input-number v-model:value="formData.type_specific_data.runway_count" :min="1" style="width: 100%" placeholder="请输入跑道数量" />
          </a-form-item>

          <a-form-item label="跑道表面">
            <a-input v-model:value="formData.type_specific_data.runway_surface" placeholder="例如：沥青、混凝土" />
          </a-form-item>

          <a-form-item label="海拔(m)">
            <a-input-number v-model:value="formData.type_specific_data.altitude" :min="0" style="width: 100%" placeholder="请输入海拔" />
          </a-form-item>

          <a-form-item label="容量(架次/天)">
            <a-input-number v-model:value="formData.type_specific_data.capacity" :min="0" style="width: 100%" placeholder="请输入容量" />
          </a-form-item>

          <a-form-item label="使用性质">
            <a-select v-model:value="formData.type_specific_data.usage_type" placeholder="请选择使用性质">
              <a-select-option value="公共">公共</a-select-option>
              <a-select-option value="军用">军用</a-select-option>
              <a-select-option value="军民合用">军民合用</a-select-option>
              <a-select-option value="私用">私用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="使用时间">
            <a-input v-model:value="formData.type_specific_data.usage_time" placeholder="例如：1997年" />
          </a-form-item>
        </template>

        <!-- 港口专用字段 -->
        <template v-if="formData.equipment_category === 'seaport'">
          <a-form-item label="占地面积(㎡)">
            <a-input-number v-model:value="formData.type_specific_data.area" :min="0" style="width: 100%" placeholder="请输入占地面积" />
          </a-form-item>

          <a-form-item label="泊位数量">
            <a-input-number v-model:value="formData.type_specific_data.berth_count" :min="1" style="width: 100%" placeholder="请输入泊位数量" />
          </a-form-item>

          <a-form-item label="最大停靠吨位">
            <a-input-number v-model:value="formData.type_specific_data.max_vessel_tonnage" :min="0" style="width: 100%" placeholder="请输入最大停靠吨位" />
          </a-form-item>

          <a-form-item label="使用性质">
            <a-select v-model:value="formData.type_specific_data.usage_type" placeholder="请选择使用性质">
              <a-select-option value="公共">公共</a-select-option>
              <a-select-option value="军用">军用</a-select-option>
              <a-select-option value="民用">民用</a-select-option>
              <a-select-option value="军民合用">军民合用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="水深(m)">
            <a-input-number v-model:value="formData.type_specific_data.water_depth" :min="0" :precision="1" style="width: 100%" placeholder="请输入水深" />
          </a-form-item>
        </template>

        <!-- 电站专用字段 -->
        <template v-if="formData.equipment_category === 'power_station'">
          <a-form-item label="占地面积(㎡)">
            <a-input-number v-model:value="formData.type_specific_data.area" :min="0" style="width: 100%" placeholder="请输入占地面积" />
          </a-form-item>

          <a-form-item label="发电量(MW)">
            <a-input-number v-model:value="formData.type_specific_data.power_generation" :min="0" style="width: 100%" placeholder="请输入发电量" />
          </a-form-item>

          <a-form-item label="容量(MW)">
            <a-input-number v-model:value="formData.type_specific_data.capacity" :min="0" style="width: 100%" placeholder="请输入容量" />
          </a-form-item>

          <a-form-item label="燃料类型">
            <a-select v-model:value="formData.type_specific_data.fuel_type" placeholder="请选择燃料类型">
              <a-select-option value="煤炭">煤炭</a-select-option>
              <a-select-option value="天然气">天然气</a-select-option>
              <a-select-option value="石油">石油</a-select-option>
              <a-select-option value="核能">核能</a-select-option>
              <a-select-option value="水力">水力</a-select-option>
              <a-select-option value="风力">风力</a-select-option>
              <a-select-option value="太阳能">太阳能</a-select-option>
            </a-select>
          </a-form-item>
        </template>

        <!-- 油田专用字段 -->
        <template v-if="formData.equipment_category === 'oil_field'">
          <a-form-item label="发现时间">
            <a-input v-model:value="formData.type_specific_data.discovery_time" placeholder="例如：1948年" />
          </a-form-item>

          <a-form-item label="开采时间">
            <a-input v-model:value="formData.type_specific_data.exploitation_time" placeholder="例如：1952年" />
          </a-form-item>

          <a-form-item label="总储量">
            <a-input v-model:value="formData.type_specific_data.total_reserves" placeholder="例如：260亿至420亿桶" />
          </a-form-item>

          <a-form-item label="年产量">
            <a-input v-model:value="formData.type_specific_data.annual_output" placeholder="例如：2.8亿吨" />
          </a-form-item>

          <a-form-item label="油田面积">
            <a-input v-model:value="formData.type_specific_data.oilfield_area" placeholder="例如：3264平方千米" />
          </a-form-item>

          <a-form-item label="主产油层">
            <a-textarea v-model:value="formData.type_specific_data.main_production_layer" :rows="2" placeholder="例如：侏罗系阿拉伯组D段石灰岩" />
          </a-form-item>
        </template>

        <!-- 火车站专用字段 -->
        <template v-if="formData.equipment_category === 'train_station'">
          <a-form-item label="车站类型">
            <a-select v-model:value="formData.type_specific_data.station_type" placeholder="请选择车站类型">
              <a-select-option value="客运站">客运站</a-select-option>
              <a-select-option value="货运站">货运站</a-select-option>
              <a-select-option value="客货站">客货站</a-select-option>
              <a-select-option value="编组站">编组站</a-select-option>
              <a-select-option value="中转站">中转站</a-select-option>
              <a-select-option value="高铁站">高铁站</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="站台数量">
            <a-input-number v-model:value="formData.type_specific_data.platform_count" :min="1" style="width: 100%" placeholder="请输入站台数量" />
          </a-form-item>

          <a-form-item label="日均列车班次">
            <a-input-number v-model:value="formData.type_specific_data.daily_trains" :min="0" style="width: 100%" placeholder="请输入日均列车班次" />
          </a-form-item>

          <a-form-item label="日均客流量(人次)">
            <a-input-number v-model:value="formData.type_specific_data.passenger_capacity" :min="0" style="width: 100%" placeholder="请输入日均客流量" />
          </a-form-item>

          <a-form-item label="货运能力(万吨/年)">
            <a-input-number v-model:value="formData.type_specific_data.freight_capacity" :min="0" style="width: 100%" placeholder="请输入货运能力" />
          </a-form-item>
        </template>
      </template>

      <!-- 海上目标专属字段 -->
      <template v-if="formData.object_type === 'sea_target'">
        <!-- 新增字段 -->
        <a-form-item label="当前位置">
          <a-input v-model:value="formData.type_specific_data.coordinates" placeholder="请输入当前位置坐标(经度,纬度)" />
        </a-form-item>

        <a-form-item label="重要程度">
          <a-select v-model:value="formData.type_specific_data.importance" placeholder="请选择重要程度">
            <a-select-option value="general">一般</a-select-option>
            <a-select-option value="important">重要</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="发现时间">
          <a-date-picker
            v-model:value="discoveryTime"
            style="width: 100%"
            placeholder="请选择发现时间"
            :format="'YYYY-MM-DD'"
            :value-format="'YYYY-MM-DD'"
          />
        </a-form-item>

        <a-divider />

        <!-- 通用海上目标字段 -->
        <a-form-item label="生产日期">
          <a-input v-model:value="formData.type_specific_data.production_date" placeholder="例如：1988—（建造）" />
        </a-form-item>

        <a-form-item label="服役时间">
          <a-input v-model:value="formData.type_specific_data.service_start_time" placeholder="例如：1991—至今" />
        </a-form-item>

        <a-form-item label="建造年份">
          <a-input-number v-model:value="formData.type_specific_data.construction_year" :min="1900" :max="2100" style="width: 100%" placeholder="请输入建造年份" />
        </a-form-item>

        <a-form-item label="排水量(吨)">
          <a-input-number v-model:value="formData.type_specific_data.displacement" :min="0" style="width: 100%" placeholder="请输入排水量" />
        </a-form-item>

        <a-form-item label="最大里程(海里)">
          <a-input-number v-model:value="formData.type_specific_data.endurance" :min="0" style="width: 100%" placeholder="请输入最大里程/续航力" />
        </a-form-item>

        <a-form-item label="最高速度(节)">
          <a-input-number v-model:value="formData.type_specific_data.max_speed" :min="0" style="width: 100%" placeholder="请输入最高速度" />
        </a-form-item>

        <a-form-item label="巡航速度(节)">
          <a-input-number v-model:value="formData.type_specific_data.cruise_speed" :min="0" style="width: 100%" placeholder="请输入巡航速度" />
        </a-form-item>

        <a-form-item label="动力系统">
          <a-input v-model:value="formData.type_specific_data.propulsion_type" placeholder="例如：4×GE LM2500 燃气轮机" />
        </a-form-item>

        <a-form-item label="武器系统">
          <a-textarea v-model:value="formData.type_specific_data.armament_text" :rows="3" placeholder="请输入武器系统描述" />
        </a-form-item>

        <a-form-item label="雷达/传感器">
          <a-select v-model:value="formData.type_specific_data.sensors" mode="tags" placeholder="请输入雷达类型（支持多选）">
            <a-select-option value="AN/SPY-1D">AN/SPY-1D</a-select-option>
            <a-select-option value="AN/SPY-6">AN/SPY-6</a-select-option>
            <a-select-option value="相控阵雷达">相控阵雷达</a-select-option>
            <a-select-option value="搜索雷达">搜索雷达</a-select-option>
            <a-select-option value="火控雷达">火控雷达</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="人员数量">
          <a-input-number v-model:value="formData.type_specific_data.crew_capacity" :min="0" style="width: 100%" placeholder="请输入人员数量" />
        </a-form-item>

        <a-form-item label="母港">
          <a-input v-model:value="formData.type_specific_data.home_port" placeholder="请输入母港" />
        </a-form-item>

        <!-- 航母特有字段 -->
        <template v-if="formData.equipment_category === 'aircraft_carrier'">
          <a-form-item label="最大载机数量">
            <a-input-number v-model:value="formData.type_specific_data.aircraft_capacity" :min="0" style="width: 100%" placeholder="请输入最大载机数量" />
          </a-form-item>

          <a-form-item label="载机数量描述">
            <a-input v-model:value="formData.type_specific_data.aircraft_capacity_text" placeholder="例如：60+ 架（典型构型）" />
          </a-form-item>

          <a-form-item label="飞行甲板信息">
            <a-textarea v-model:value="formData.type_specific_data.flight_deck_info" :rows="2" placeholder="请输入飞行甲板信息" />
          </a-form-item>
        </template>
      </template>

      <!-- 陆上目标专属字段 -->
      <template v-if="formData.object_type === 'land_target'">
        <!-- 新增字段 -->
        <a-form-item label="当前位置">
          <a-input v-model:value="formData.type_specific_data.coordinates" placeholder="请输入当前位置坐标(经度,纬度)" />
        </a-form-item>

        <a-form-item label="重要程度">
          <a-select v-model:value="formData.type_specific_data.importance" placeholder="请选择重要程度">
            <a-select-option value="general">一般</a-select-option>
            <a-select-option value="important">重要</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="发现时间">
          <a-date-picker
            v-model:value="discoveryTime"
            style="width: 100%"
            placeholder="请选择发现时间"
            :format="'YYYY-MM-DD'"
            :value-format="'YYYY-MM-DD'"
          />
        </a-form-item>

        <a-divider />

  
        <!-- 军事设施专属字段 -->
        <template v-if="formData.equipment_category === 'military_facility'">
          <a-form-item label="占地面积(㎡)">
            <a-input-number v-model:value="formData.type_specific_data.site_area" :min="0" :precision="0" style="width: 100%" placeholder="请输入占地面积" />
          </a-form-item>

          <a-form-item label="建筑面积(㎡)">
            <a-input-number v-model:value="formData.type_specific_data.building_area" :min="0" :precision="0" style="width: 100%" placeholder="请输入建筑面积" />
          </a-form-item>

          <a-form-item label="主要功能">
            <a-select v-model:value="formData.type_specific_data.main_function" placeholder="请选择主要功能">
              <a-select-option value="指挥中心">指挥中心</a-select-option>
              <a-select-option value="训练基地">训练基地</a-select-option>
              <a-select-option value="后勤保障">后勤保障</a-select-option>
              <a-select-option value="作战基地">作战基地</a-select-option>
              <a-select-option value="情报中心">情报中心</a-select-option>
              <a-select-option value="通信枢纽">通信枢纽</a-select-option>
              <a-select-option value="防空基地">防空基地</a-select-option>
              <a-select-option value="导弹基地">导弹基地</a-select-option>
              <a-select-option value="雷达站">雷达站</a-select-option>
              <a-select-option value="维修基地">维修基地</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="建设年份">
            <a-input-number v-model:value="formData.type_specific_data.construction_year" :min="1900" :max="2030" style="width: 100%" placeholder="请输入建设年份" />
          </a-form-item>
        </template>

        <!-- 其他陆上目标通用字段 -->
        <template v-else>
          <a-form-item label="重量(t)">
            <a-input-number v-model:value="formData.type_specific_data.weight" :min="0" :precision="1" style="width: 100%" placeholder="请输入重量" />
          </a-form-item>

          <a-form-item label="长度(m)">
            <a-input-number v-model:value="formData.type_specific_data.length" :min="0" :precision="1" style="width: 100%" placeholder="请输入长度" />
          </a-form-item>

          <a-form-item label="宽度(m)">
            <a-input-number v-model:value="formData.type_specific_data.width" :min="0" :precision="1" style="width: 100%" placeholder="请输入宽度" />
          </a-form-item>

          <a-form-item label="高度(m)">
            <a-input-number v-model:value="formData.type_specific_data.height" :min="0" :precision="1" style="width: 100%" placeholder="请输入高度" />
          </a-form-item>

          <a-form-item label="最大速度(km/h)">
            <a-input-number v-model:value="formData.type_specific_data.max_speed" :min="0" style="width: 100%" placeholder="请输入最大速度" />
          </a-form-item>

          <a-form-item label="人员数量">
            <a-input-number v-model:value="formData.type_specific_data.crew" :min="0" style="width: 100%" placeholder="请输入人员数量" />
          </a-form-item>
        </template>
      </template>

      
      <!-- 其他信息部分 -->
      <a-divider orientation="left">其他信息</a-divider>

      <a-form-item label="感知能力详情" name="perception_capability">
        <a-textarea
          v-model:value="formData.perception_capability"
          :rows="1"
          placeholder="请输入感知能力详情，如：雷达探测、红外成像、声纳定位等"
          show-count
          :maxlength="200"
        />
      </a-form-item>

      <a-form-item label="通信能力详情" name="communication_capability">
        <a-textarea
          v-model:value="formData.communication_capability"
          :rows="1"
          placeholder="请输入通信能力详情，如：卫星通信、短波通信、数据链传输等"
          show-count
          :maxlength="200"
        />
      </a-form-item>

      <a-form-item label="适用场景" name="applicable_scenarios">
        <a-textarea
          v-model:value="formData.applicable_scenarios"
          :rows="1"
          placeholder="请输入适用场景，如：城市环境、山地作战、海面巡逻、边境监控等"
          show-count
          :maxlength="200"
        />
      </a-form-item>

      <a-form-item label="地理位置信息" name="location">
        <a-textarea
          v-model:value="formData.location"
          :rows="1"
          placeholder="请输入地理位置信息，如：经纬度坐标、行政区划、具体地址等"
          show-count
          :maxlength="200"
        />
      </a-form-item>

      <a-form-item label="标签">
        <a-select
          v-model:value="formData.tags"
          mode="tags"
          placeholder="请输入标签"
          style="width: 100%"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { createSituationObject, updateSituationObject, getEquipmentCategories } from '@/apis'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: null
  },
  objectTypes: {
    type: Array,
    default: () => []
  },
  deploymentStatuses: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:open', 'success'])

const formRef = ref()
const loading = ref(false)
const isEdit = computed(() => !!props.editData)
const equipmentCategories = ref([])

// 创建独立的日期字段 ref，避免深层响应式问题
const discoveryTime = ref(null)
const launchTime = ref(null)

const formData = reactive({
  object_type: undefined,
  equipment_category: undefined, // 新增装备类别字段
  name: '',
  code: '',
  description: '',
  model: '',
  organization: '',
  deployment_status: undefined,
  perception_capability: '',
  communication_capability: '',
  applicable_scenarios: '',
  location: '',
  type_specific_data: {},
  tags: []
})

// 填充编辑数据
async function fillEditFormData() {
  if (!props.editData) {
    console.log('没有编辑数据，返回')
    return
  }

  console.log('开始填充编辑数据，完整数据:', props.editData)
  console.log('当前对象类型:', props.editData.object_type)
  console.log('当前装备类别:', props.editData.equipment_category)

  // 编辑模式：填充数据
  const typeSpecificData = props.editData.type_specific_data || {}

  let processedTypeSpecificData = { ...typeSpecificData }

  // 处理日期字段，设置独立的 ref
  discoveryTime.value = processedTypeSpecificData.discovery_time || null
  launchTime.value = processedTypeSpecificData.launch_time || null

  Object.assign(formData, {
    object_type: props.editData.object_type,
    equipment_category: props.editData.equipment_category || undefined,
    name: props.editData.name,
    code: props.editData.code,
    description: props.editData.description || '',
    model: props.editData.model,
    organization: props.editData.organization,
    deployment_status: props.editData.deployment_status,
    perception_capability: props.editData.perception_capability || '',
    communication_capability: props.editData.communication_capability || '',
    applicable_scenarios: props.editData.applicable_scenarios || '',
    location: props.editData.location || '',
    type_specific_data: processedTypeSpecificData,
        tags: props.editData.tags || []
    })

  // 确保装备类别已加载，等待加载完成后再填充数据
  if (equipmentCategories.value.length === 0 && props.editData.object_type) {
    console.log('装备类别为空，开始加载:', props.editData.object_type)
    await loadEquipmentCategories(props.editData.object_type)
    console.log('装备类别加载完成，当前数据:', equipmentCategories.value)

    // 重新填充表单数据，确保装备类别选择器能正确显示
    Object.assign(formData, {
      equipment_category: props.editData.equipment_category || undefined
    })
    console.log('重新设置装备类别后，formData:', formData)
    console.log('装备类别选择器应该显示:', {
      value: formData.equipment_category,
      availableOptions: equipmentCategories.value,
      matchingLabel: equipmentCategories.value.find(cat => cat.value === formData.equipment_category)?.label
    })
  }

  console.log('编辑数据填充完成:', formData)
}

// 监听弹窗打开，初始化表单
watch(() => props.open, async (val) => {
  if (val) {
    await nextTick()
    if (props.editData) {
      // 编辑模式：等待填充数据完成（包括装备类别加载）
      await fillEditFormData()
    } else {
      // 新建模式：重置表单
      resetForm()
    }
  }
})

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate()

    // 如果是观测装备，将装备类别保存到类型特定数据中
    if (formData.object_type === 'observation_equipment' && formData.equipment_category) {
      formData.type_specific_data.equipment_category = formData.equipment_category
    }

    
    // 处理日期字段，将独立的 ref 合并到 type_specific_data
    formData.type_specific_data.discovery_time = discoveryTime.value
    formData.type_specific_data.launch_time = launchTime.value

    
    loading.value = true

    if (isEdit.value) {
      await updateSituationObject(props.editData.id, formData)
      message.success('更新成功')
    } else {
      await createSituationObject(formData)
      message.success('创建成功')
    }

    emit('success')
    emit('update:open', false)
  } catch (error) {
    if (error.errorFields) {
      message.error('请完善表单信息')
    } else {
      message.error('操作失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 取消
function handleCancel() {
  emit('update:open', false)
  resetForm()
}

// 重置表单
function resetForm() {
  Object.assign(formData, {
    object_type: undefined,
    equipment_category: undefined,
    name: '',
    code: '',
    description: '',
    model: '',
    organization: '',
    deployment_status: undefined,
    perception_capability: '',
    communication_capability: '',
    applicable_scenarios: '',
    location: '',
    type_specific_data: {},
    tags: []
  })

  // 重置独立的日期 ref
  discoveryTime.value = null
  launchTime.value = null

  formRef.value?.resetFields()
}

// 获取类型标签
function getTypeLabel(type) {
  const found = props.objectTypes.find(t => t.value === type)
  return found ? found.label : type
}

// 处理对象类型变化
async function handleObjectTypeChange(value) {
  // 只在新建模式下清空装备类别和类型特定数据
  if (!isEdit.value) {
    formData.equipment_category = undefined
    formData.type_specific_data = {}
  }

  // 加载对应的装备类别
  await loadEquipmentCategories(value)
}

// 处理装备类别变化
function handleEquipmentCategoryChange(value) {
  // 只在新建模式下清空类型特定数据
  if (!isEdit.value) {
    formData.type_specific_data = {}
  }
}


// 载荷管理函数
function addPayload() {
  if (!formData.type_specific_data.payload) {
    formData.type_specific_data.payload = []
  }
  formData.type_specific_data.payload.push({
    type: '',
    resolution: '',
    swath: ''
  })
}

function removePayload(index) {
  if (formData.type_specific_data.payload && formData.type_specific_data.payload.length > index) {
    formData.type_specific_data.payload.splice(index, 1)
  }
}

// 加载装备类别
async function loadEquipmentCategories(objectType) {
  console.log('开始加载装备类别:', objectType)
  if (!objectType) {
    equipmentCategories.value = []
    return
  }

  try {
    const response = await getEquipmentCategories(objectType)
    console.log('获取装备类别API响应:', response)

    // 处理响应数据
    if (response && response.object_type && response.categories && Array.isArray(response.categories)) {
      // 单个对象类型响应（当指定了 object_type 参数时）
      equipmentCategories.value = response.categories.map(category => ({
        value: category.value,
        label: category.label
      }))
      console.log('装备类别加载成功（单个响应）:', equipmentCategories.value)
    } else if (response && response.categories && Array.isArray(response.categories)) {
      // 多个对象类型响应（当未指定 object_type 参数时）
      const typeCategories = response.categories.find(item => item.object_type === objectType)
      if (typeCategories && typeCategories.categories.length > 0) {
        equipmentCategories.value = typeCategories.categories.map(category => ({
          value: category.value,
          label: category.label
        }))
        console.log('装备类别加载成功（数组响应）:', equipmentCategories.value)
      } else {
        equipmentCategories.value = []
        console.warn('未找到装备类别或类别为空:', typeCategories)
      }
    } else {
      equipmentCategories.value = []
      console.warn('API响应格式不正确:', response)
    }

    // 调试：验证装备类别数据完整性
    console.log('装备类别数据验证:', {
      objectType,
      categoriesCount: equipmentCategories.value.length,
      categories: equipmentCategories.value,
      hasSatellite: equipmentCategories.value.some(cat => cat.value === 'satellite'),
      satelliteLabel: equipmentCategories.value.find(cat => cat.value === 'satellite')?.label
    })
  } catch (error) {
    console.error('获取装备类别失败:', error)
    equipmentCategories.value = []
  }
}

// 初始化
onMounted(async () => {
  // 调试信息：显示初始化状态
  console.log('表单初始化开始:', {
    isEdit: isEdit.value,
    objectTypes: props.objectTypes,
    editData: props.editData,
    isOpen: props.open
  })

  // 如果组件一打开就是编辑模式，预加载装备类别
  if (props.open && isEdit.value && props.editData?.object_type) {
    console.log('组件初始化时就是编辑模式，预加载装备类别:', props.editData.object_type)
    await loadEquipmentCategories(props.editData.object_type)
    console.log('预加载装备类别完成:', equipmentCategories.value)
  }
})
</script>

<style scoped>
:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
  margin: 16px 0;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
